﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Data.SqlClient;

namespace WebApplication1
{
    public partial class data1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string requestCmd = Request.QueryString["sng"];
            if (requestCmd != null && requestCmd.ToString() != "")
                getSngList(requestCmd);

            string requestCurrentSng = Request.QueryString["playSng"];
            if (requestCurrentSng != null && requestCurrentSng.ToString() != "")
            {
                playCurrentSng(requestCurrentSng, Request.QueryString["currentSngTitle"].ToString(), Request.QueryString["currentArtist"].ToString());
            }

            switch (Request.QueryString["value"])
            {

                case "Play":
                    saveDetails();
                    break;
                case "ListAlbum":
                    getAlbumList();
                    break;
                case "listRecentVideo":
                    getRecentVideo();
                    break;
            }
        }


        void saveDetails()
        {
            XmlDocument xdoc = new XmlDocument();
            XmlTextReader reader = new XmlTextReader("http://rss.songs.pk/");
            xdoc.Load(reader);
            XmlNodeList xtitle = xdoc.GetElementsByTagName("title");
            XmlNodeList xlink = xdoc.GetElementsByTagName("link");
            XmlNodeList xalbumCover = xdoc.GetElementsByTagName("description");
            string title = "<br/>";
            string[] album = new string[50];
            string[] link = new string[50]; //stores the movie links
            string[] albumCover = new string[50];// stroes the album links
            string temp = "";
            for (int i = 1; i < xtitle.Count; i++)
            {
                int idx = xtitle[i].InnerText.IndexOf("-");
                if (idx != -1)
                    temp = xtitle[i].InnerText.Remove(idx);
                else
                    temp = xtitle[i].InnerText;//<a href="#" onclick="sendRequest('Play');return false;">Play</a>
                temp = temp.Trim();
                title += "<a  href='#' onclick=\"sendSngRequest('" + temp + "'); return false;\">" + temp + "</a><br/>";
                album[i] = temp;
                link[i] = xlink[i].InnerText;

                albumCover[i] = xalbumCover.Item(i - 1).ChildNodes[0].InnerText; //xalbumCover[2].InnerText;
                albumCover[i] = albumCover[i].Substring(albumCover[i].ToLower().IndexOf("src=\"http"), albumCover[i].ToLower().IndexOf("alt") - albumCover[i].ToLower().IndexOf("src=\"http"));
                albumCover[i] = albumCover[i].Replace("src=", "");
                albumCover[i] = albumCover[i].Replace("\"", "");
            }



            int no = 0;
            string webDat = "";
            string[] sng = new string[30];
            string[] sngTitle = new string[30];
            string[] sngArtist = new string[30];
            int indx = 0;
            for (indx = 1; indx < xtitle.Count; indx++)
            {
                Connection myConnection = new Connection();
                SqlConnection conn = myConnection.connect();
                SqlCommand chk = myConnection.sqlCmd(conn, System.Data.CommandType.StoredProcedure);

                chk.CommandText = "checkAudio";
                chk.Parameters.Clear();
                chk.Parameters.AddWithValue("@album", album[indx]);
                if (chk.ExecuteScalar() == null)
                {
                    System.Net.WebClient clien = new System.Net.WebClient();
                    webDat = clien.DownloadString(link[indx]);
                    clien.Dispose();
                    no = 0;
                    while (1 == 1)
                    {
                        try
                        {
                            webDat = webDat.Substring(webDat.ToLower().IndexOf("http://link"));

                            sngArtist[no] = webDat.Substring(webDat.ToLower().IndexOf("http://link"), (webDat.ToLower().IndexOf("</td>") + 11) - webDat.ToLower().IndexOf("http://link"));
                            webDat = webDat.Replace(sngArtist[no], "");

                            sng[no] = sngArtist[no].Substring(sngArtist[no].ToLower().IndexOf("http://link"), (sngArtist[no].ToLower().IndexOf("songid=") + 11) - sngArtist[no].ToLower().IndexOf("http://link"));
                            sngArtist[no] = sngArtist[no].Substring(sngArtist[no].ToLower().IndexOf(sng[no]) + sng[no].Length);

                            sngTitle[no] = sngArtist[no].Substring(2, sngArtist[no].ToLower().IndexOf("</a>") - 2);
                            sngTitle[no] = sngTitle[no].Trim();

                            sngArtist[no] = sngArtist[no].Substring(sngArtist[no].ToLower().IndexOf("<i>") + 3, (sngArtist[no].ToLower().IndexOf("</i>") - sngArtist[no].ToLower().IndexOf("<i>") - 3));
                            sngArtist[no] = sngArtist[no].Trim();
                            no += 1;
                        }
                        catch
                        {
                            break;
                        }
                    }

                    chk.Parameters.Clear();
                    chk.Parameters.AddWithValue("@album", album[indx]);
                    chk.Parameters.AddWithValue("@date", Convert.ToDateTime(DateTime.UtcNow));
                    chk.Parameters.AddWithValue("@albumCover", albumCover[indx]);
                    chk.CommandText = "saveAlbum";
                    chk.CommandType = System.Data.CommandType.StoredProcedure;
                    chk.ExecuteNonQuery();

                    for (int i1 = 0; i1 < no; i1++)
                    {
                        chk.Parameters.Clear();
                        chk.Parameters.AddWithValue("@album", album[indx]);
                        chk.Parameters.AddWithValue("@song", sng[i1]);
                        chk.Parameters.AddWithValue("@sngArtist", sngArtist[i1]);
                        chk.Parameters.AddWithValue("@sngTitle", sngTitle[i1]);
                        chk.CommandText = "saveSng";
                        chk.CommandType = System.Data.CommandType.StoredProcedure;
                        chk.ExecuteNonQuery();
                    }
                }
            }
            //   sng[0] = "http://uploads.mp3rocketupload.com/1017709.mp3";
            int sel = 3;
            switch (Request.QueryString["value"])
            {
                case "Play":
                    {

                        Response.Write("albumList|<div id='example' ><span class='mb_audio'><object width='300' height='24' type='application/x-shockwave-flash' style='outline: medium none; visibility: visible;' data='player.swf'><param name='menu' value='false'><param name='flashvars' value='soundFile=" + sng[sel] + "&amp;titles=" + sngTitle[sel] + "'><param name='wmode' value='transparent'><param name='allowscriptaccess' value='always'><embed src='player.swf' type='application/x-shockwave-flash' wmode='transparent' allowscriptaccess='always' width='300' height='24' flashvars='soundFile=" + sng[sel] + "&amp;titles=" + sngTitle[sel] + "'></object></span><br/><br/></div><img class='albumImg' src='" + albumCover[indx - 1] + "'/><a>" + title + "      " + sng[sel] + sngTitle[sel] + sngArtist[sel] + albumCover[indx - 1] + "</a>" + no);

                        break;
                    }
                case "listSong":
                    Response.Write("songList|");
                    break;
            }
        }

        void getSngList(string albumTitle)
        {

            Connection myConnection = new Connection();
            SqlConnection conn = myConnection.connect();
            SqlCommand chk = myConnection.sqlCmd(conn, System.Data.CommandType.StoredProcedure);

            chk.CommandText = "checkAudio";
            chk.Parameters.Clear();
            chk.Parameters.AddWithValue("@album", albumTitle);
            chk.CommandType = System.Data.CommandType.StoredProcedure;
            if (chk.ExecuteScalar() != null)
            {
                chk.Parameters.Clear();
                chk.CommandText = "selectSng";
                chk.Parameters.AddWithValue("@album", albumTitle);
                SqlDataReader rdr = chk.ExecuteReader();
                string songList = "";
                string coverURL = "";
                while (rdr.Read())
                {
                    string cTitle = rdr["sngTitle"].ToString();
                    cTitle=cTitle.Replace(" ", "_");
                    songList +=
                 "<a href='javascript:void(0)' onclick= changeNplay('" + rdr["song"] + "','" + cTitle + "')>" + "<b>► </b>" + rdr["sngTitle"] + " - <i>" + rdr["sngArtist"].ToString() + "</i></a><br/>";
                    coverURL = rdr["albumCover"].ToString();
                }




                Response.Write("songList|<img class='albumImg' src='" + coverURL + "'/><br/><br/><div class='songList'>" + songList + "</div>|title|none|title|" + albumTitle);


            }
            else
                Response.Write("songList|");

            conn.Close();
        }

        void playCurrentSng(string sngLink, string sngTitle, string sng)
        {
            Response.Write("playSong|<div id='player'>hi</div><span class='nowPlaying' >Now Playing <b>" + sngTitle + "</b><br/>From <b>" + sng + "</b></span><br/>|songListScript|<script " + ">" + "{var flashvars = {}; flashvars.autostart='yes'; flashvars.soundFile = '" + sngLink + "';flashvars.titles = '" + sng + "';	flashvars.artists =  '" + sngTitle + "'; var params = {};  var attributes = {}; attributes.id = 'flplayer'; swfobject.embedSWF('player.swf', 'player', '100%', '40px', '9.0.0', false, flashvars, params, attributes);} </script" + "><div id='player'></div>");

        }

        void getAlbumList()
        {
            Connection myConnection = new Connection();
            SqlConnection conn = myConnection.connect();
            SqlCommand chk = myConnection.sqlCmd(conn, System.Data.CommandType.StoredProcedure);


            chk.CommandText = "getAlbumData";
            chk.Parameters.Clear();
            SqlDataReader rdr = chk.ExecuteReader();
            string albumList = "<br/>";
            while (rdr.Read())
            {//<a href="#" onclick="sendRequest('Play');return false;">Play</a>
                albumList += "<li><a  href='#' onclick=\"sendSngRequest('" + rdr["album"] + "'); return false;\">" + rdr["album"] + "</a></li>";
            }
            Response.Write("albumList|" + albumList);

            conn.Close();
        }

        // ------------------------Video-------------------------------
        void getRecentVideo()
        {
            Response.Write("recentVideoList|<h3>video option will be available shortly</h3>|mBoxVideo|<script> sendRequest('ListAlbum');</script" + ">");

        }
    
    }
}